/*
 * Copyright (c) 2014. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package com.dc.gameserver.extComponents.Kit.propEncrypt;

import sun.misc.BASE64Decoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class KeyTransformer {

    /**
     * MD5 Message Digest
     */
    private MessageDigest messageDigestMD5 = null;

    /**
     * SHA1 Message Digest
     */
    private MessageDigest messageDigestSHA1 = null;

    /**
     * SecureRandom
     */
    private SecureRandom secureRandom = null;

    /**
     * 构造函数
     */
    public KeyTransformer() {
        super();
        secureRandom = new SecureRandom();
        try {
            messageDigestMD5 = MessageDigest.getInstance("MD5");
            messageDigestSHA1 = MessageDigest.getInstance("SHA1");
            new BASE64Decoder();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过key得到128位的md5 digest（key）
     *
     * @param key
     * @return
     */
    public byte[] getMD5Digest(String key) {

        messageDigestMD5.reset();
        try {
            messageDigestMD5.update(key.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return messageDigestMD5.digest();
    }

    /**
     * 随机得到128位的key
     *
     * @return
     */
    public byte[] getRandomKey() {
        byte[] keyBytes = new byte[16];
        secureRandom.nextBytes(keyBytes);
        return keyBytes;
    }

    /**
     * 通过key得到128位的sha1 digest（key）
     *
     * @param key
     * @return
     */
    public byte[] getSHA1Digest128Bit(String key) {

        byte[] keyBytes = new byte[16];
        messageDigestSHA1.reset();
        try {
            messageDigestSHA1.update(key.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.arraycopy(messageDigestSHA1.digest(), 0, keyBytes, 0, 16);
        return keyBytes;
    }
}
